from flask import (
    Blueprint,
    request
)
from network import (
    success_response,
    req_data_miss_parameter,
    parse_data,
)
from network.NetworkModel_pb2 import (
    LiveStartRequest,
    PBEmpty,
    FeedItem
)
from utils import RedisOperation, ImageTool
from user_common.models import User
from feeds.models import Feed
from time import time


bp = Blueprint('live', __name__, url_prefix='/live')


@bp.route('/livestart/', methods=['POST'])
def live_start():
    req = parse_data(LiveStartRequest(), request)
    user = User.query.filter_by(id=req.uid).first()
    if user is None:
        return req_data_miss_parameter("uid不存在")
    feed = Feed.query.filter_by(id=req.fid).first()
    if feed is None:
        return req_data_miss_parameter("fid不存在")
    filename = 'snapshot{}{}'.format(user.id, int(time()))
    snapshotUrl = ImageTool(720, 1280, 'snapshot', filename).process_image(req.imageData)
    item = FeedItem()
    item.snapshotUrl = snapshotUrl
    item.avatarUrl = user.avatarUrl
    item.name = user.name
    item.roomTitle = req.roomTitle
    item.ruid = str(user.id)
    item.fid = str(feed.id)

    rdm = RedisOperation(db=int(req.fid))
    rdm.set_data(user.id, item.SerializeToString(), 60)

    return success_response(item)

